If you have ecommerce website and you want to accept payment via credit card or debit card from your website then 2Checkout Payment Gateway is the easy solution. In this article, i will show you an easy way to integrate 2Checkout Payment Gateway in web application or ecommerce website.
The 2Checkout Payment API allows you to accept payment via credit cards or debit card on your website. With 2Checkout Gateway, your website user or customer can make payment through their credit or debit card.
If you are a Web Developer and want to integrate 2Checkout Payment Gateway, 2Checkout PHP library helps you to connect the Payment API and process the credit or debit card payment. Now i will explain you step by step process to integrate 2Checkout payment gateway in PHP for accept payment online with credit or debit card.
How to create 2Checkout Sandbox Account:
2Checkout sandbox account provide a testing environment to test 2Checkout integration process. Before make 2Checkout payment gateway live or production mode, you need to test the gateway integration in sandbox environment. you need to follow the below steps to generate 2Checkout payment Gateway API Keys in Sandbox Account. We will use this API Keys to test the credit or debit card payment process with 2Checkout Gateway API.
Step-1: Login or Signup (if you don’t have account) into your 2Checkout Sandbox account.
Step-2: After Login you will get an API tab in top bar Menu, Click on API Menu.
Step-3: Go to API Page and generate API Keys. In Key Generation section, you will get Publishable Key and Private Key. Copy both keys and save it in your notepad for later use in the script.
Now First we need to create a Database Table to store order transaction details.
Following Sql query will create “order_transaction” table with some basic field in mysql database
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
CREATE TABLE `order_transaction` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `card_num` bigint(20) NOT NULL, `card_exp_month` int(2) NOT NULL, `card_exp_year` year(4) NOT NULL, `card_cvv` int(3) NOT NULL, `item_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `item_number` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `item_price` float(10,2) NOT NULL, `currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `paid_amount` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `order_number` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `txn_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `payment_status` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
To connect our database we need to create Database Configuration file (dbconfig.php).
dbconfig.php file will contain database host ($host ), username ($dbuser ), password ($dbpass) and database name ($dbname) mysql server credentials.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php // Database configuration $host = "localhost"; $dbuser = "root"; $dbpass = ""; $dbname = "tutorialswebsite"; // Create database connection $db = new mysqli($host, $dbuser, $dbpass, $dbname); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); } ?> |
Create 2Checkout Payment Form (index.php)
You need to create payment form that allow buyer to submit their details like email, name on card, card number, expiration month and year, and CVC.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<div class="col-xs-12 col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Charge $10 USD with 2Checkout</h3> </div> <div class="panel-body"> <!-- display errors returned by createToken --> <p class="payment-status"></p> <form id="paymentForm" method="post" action="submitPayment.php"> <div class="form-group"> <label>NAME</label> <input type="text" class="form-control" name="name" id="name" placeholder="Enter name" required="" autofocus=""> </div> <div class="form-group"> <label>EMAIL</label> <input type="email" class="form-control" name="email" id="email" placeholder="Enter email" required=""> </div> <div class="form-group"> <label>CARD NUMBER</label> <input type="text" class="form-control" name="card_num" id="card_num" placeholder="Enter card number" autocomplete="off" required=""> </div> <div class="row"> <div class="col-xs-8"> <div class="form-group"> <label style="display: block;">EXPIRY DATE</label> <div class="col-xs-6"> <input type="number" name="exp_month" id="exp_month" class="form-control" style="padding: 6px 10px;" placeholder="MM" required=""> </div> <div class="col-xs-6"> <input type="number" name="exp_year" id="exp_year" class="form-control" style="padding: 6px 10px;" placeholder="YY" required=""> </div> </div> </div> <div class="col-xs-4 pull-right"> <div class="form-group"> <label>CVV</label> <input type="number" name="cvv" id="cvv" class="form-control" autocomplete="off" required=""> </div> </div> </div> <!-- hidden token input --> <input id="token" name="token" type="hidden" value=""> <!-- submit button --> <input type="submit" class="btn btn-success btn-lg btn-block" value="Submit Payment"> </form> </div> </div> </div> |
Include the jQuery library and 2Checkout javascript library to create the token request. put below library under tag.
2 3 4 5 6 7 8 |
<!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!-- 2Checkout JavaScript library --> <script src="https://www.2checkout.com/checkout/api/2co.min.js"></script> |
Also copy and paste following javascript code under tag or before tag. Following javascript code will handle the token request call and attached the token input to credit or debit card form before submission data.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<script> // Called when token created successfully. var successCallback = function(data) { var payForm = document.getElementById('paymentForm'); // Set the token as the value for the token input payForm.token.value = data.response.token.token; // Submit the form payForm.submit(); }; // Called when token creation fails. var errorCallback = function(data) { if (data.errorCode === 200) { tokenRequest(); } else { alert(data.errorMsg); } }; var tokenRequest = function() { // Setup token request arguments var args = { sellerId: "sandbox-seller-id", //sandbox-seller-id is (Account Number publishableKey: "sandbox-publishable-key", //sandbox-publishable-key is (Publishable Key) ccNo: $("#card_num").val(), cvv: $("#cvv").val(), expMonth: $("#exp_month").val(), expYear: $("#exp_year").val() }; // Make the token request TCO.requestToken(successCallback, errorCallback, args); }; $(function() { // Pull in the public encryption key for our environment TCO.loadPubKey('sandbox'); $("#paymentForm").submit(function(e) { // Call our token request function tokenRequest(); // Prevent form from submitting return false; }); }); </script> |
2Checkout PHP Library:
The 2Checkout PHP library is required to process the card transaction using Payment Gateway API. All the library files are included in our source code, so don’t need to download ir separately.
Create (submitPayment.php) file to Validate and Process Payment:
Once the token and credit or debit card information has been submitted to server-side script (submitPayment.php), the amount charge authorization is processed using 2Checkout PHP Library.
How to Validate and Process Payment?
- First we Get token, credit or debit card details and user info form the submitted payment form using POST Method in PHP.
- Include the 2Checkout PHP library
- Now Configure your API credentials (Private Key and SellerId).
- Make an array with buyer sale parameters and pass it in auth() function of Twocheckout_Charge class for authorization.
- Create a payment charge and retrieve the charge details.
- if payment charge is successful then insert the order and transaction details in database table “order_transaction” using PHP and MySql script.
- Display the payment success status with Order ID, Order Number, order total and transaction ID to the buyer.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
<?php // Check whether token is not empty if(!empty($_POST['token'])){ // Token info $token = $_POST['token']; // Card info $card_num = $_POST['card_num']; $card_cvv = $_POST['cvv']; $card_exp_month = $_POST['exp_month']; $card_exp_year = $_POST['exp_year']; // Buyer info $name = $_POST['name']; $email = $_POST['email']; $phoneNumber = '555-555-5555'; $addrLine1 = '123 Test St'; $city = 'Columbus'; $state = 'OH'; $zipCode = '43123'; $country = 'USA'; // Item info $itemName = 'Premium Script tutorialswebsite'; $itemNumber = 'TWPS235'; $itemPrice = '10.00'; $currency = 'USD'; $orderID = 'SKA92712382139'; // Include 2Checkout PHP library require_once("2checkout-php/Twocheckout.php"); // Set API key Twocheckout::privateKey('sandbox-private-key'); Twocheckout::sellerId('sandbox-seller-id'); Twocheckout::sandbox(true); try { // Charge a credit card $charge = Twocheckout_Charge::auth(array( "merchantOrderId" => $orderID, "token" => $token, "currency" => $currency, "total" => $itemPrice, "billingAddr" => array( "name" => $name, "addrLine1" => $addrLine1, "city" => $city, "state" => $state, "zipCode" => $zipCode, "country" => $country, "email" => $email, "phoneNumber" => $phoneNumber ) )); // Check whether the charge is successful if ($charge['response']['responseCode'] == 'APPROVED') { // Order details $orderNumber = $charge['response']['orderNumber']; $total = $charge['response']['total']; $transactionId = $charge['response']['transactionId']; $currency = $charge['response']['currencyCode']; $status = $charge['response']['responseCode']; // Include database config file include_once 'dbconfig.php'; // Insert order info to database $sql = "INSERT INTO order_transaction(name, email, card_num, card_cvv, card_exp_month, card_exp_year, item_name, item_number, item_price, currency, paid_amount, order_number, txn_id, payment_status, created, modified) VALUES('".$name."', '".$email."', '".$card_num."', '".$card_cvv."', '".$card_exp_month."', '".$card_exp_year."', '".$itemName."', '".$itemNumber."','".$itemPrice."', '".$currency."', '".$total."', '".$orderNumber."', '".$transactionId."', '".$status."', NOW(), NOW())"; $insert = $db->query($sql); $insert_id = $db->insert_id; $statusMsg = '<h2>Thanks for your Order!</h2>'; $statusMsg .= '<h4>The transaction was successful. Order details are given below:</h4>'; $statusMsg .= "<p>Order ID: {$insert_id}</p>"; $statusMsg .= "<p>Order Number: {$orderNumber}</p>"; $statusMsg .= "<p>Transaction ID: {$transactionId}</p>"; $statusMsg .= "<p>Order Total: {$total} {$currency}</p>"; } } catch (Twocheckout_Error $e) { $statusMsg = '<h2>Transaction failed!</h2>'; $statusMsg .= '<p>'.$e->getMessage().'</p>'; } }else{ $statusMsg = "<p>Error with Form submission.</p>"; } ?> <!DOCTYPE html> <html lang="en-US"> <head> <title>2Checkout Payment Status</title> <meta charset="utf-8"> </head> <body> <div class="container"> <!-- Display payment status --> <?php echo $statusMsg; ?> <p><a href="index.php">Back to Home</a></p> </div> </body> </html> |
Test Card Details for 2Checkout Payment:
To test the 2Checkout payment API integration, use any of the following test credit card information.
2 3 4 5 6 |
Credit Card Number: 4000000000000002 Expiration date: 10/2020 cvv: 123 |
Use the following card information to test a failed authorization.
2 3 4 5 6 |
Credit Card Number: 4333433343334333 Expiration date: 10/2020 cvv: 123 |
Make 2Checkout Payment Gateway Live
After complete testing with Sandbox details, Make the 2Checkout payment gateway live for production mode.
- Login into your 2Checkout live account and go to API page
- Generate live API Keys (Publishable key and Private Key) and replace keys with sandbox keys details.
- Change sellerId (Account Number) and publishableKey (Publishable key) in “index.php” file as per you live 2Checkout account
- Set production key in loadPubKey() method.
234TCO.loadPubKey('production'); - Also change sellerid and Private Key in submitPayment.php file as per 2Checkout Live account credentials.
2345Twocheckout::privateKey('live-private-key');Twocheckout::sellerId('live-seller-id'); - Set false in sandbox() in submitPayment.php file
234Twocheckout::sandbox(false);
Conclusion
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co